package com.gewu.pm.ui.activity.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.CategoryTypeBean;
import com.gewu.pm.bean.GoodsBean;
import com.gewu.pm.bean.LabelBean;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.promotion.PromotionProductActivity;
import com.gewu.pm.ui.adapter.order.CategoryTypeAdapter;
import com.gewu.pm.ui.adapter.order.GoodsAdapter;
import com.gewu.pm.ui.adapter.order.LabelAdapter;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.utils.eventbus.EventCode;
import com.gewu.pm.widget.StatusLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 新增商品页面
 */
public final class AddGoodsActivity extends AppActivity
        implements OnRefreshLoadMoreListener,
        CategoryTypeAdapter.OnCategoryClickListener,
        LabelAdapter.OnLabelClickListener,
        GoodsAdapter.OnQuantityChangeListener,
        GoodsAdapter.OnGoodsClickListener {

    private EditText mSearchEdit;
    private RecyclerView mCategoryRecyclerView;
    private RecyclerView mLabelRecyclerView;
    private RecyclerView mGoodsRecyclerView;
    private SmartRefreshLayout mRefreshLayout;
    private StatusLayout mEmptyView;
    private LinearLayout mSortComprehensive;
    private LinearLayout mSortPrice;
    private ImageView mComprehensiveUp;
    private ImageView mComprehensiveDown;
    private ImageView mPriceUp;
    private ImageView mPriceDown;
    private CheckBox mOnlyInStockCheckBox;
    private TextView mTotalQuantityView;
    private TextView mConfirmButton;

    private CategoryTypeAdapter mCategoryAdapter;
    private LabelAdapter mLabelAdapter;
    private GoodsAdapter mGoodsAdapter;

    /** 分类列表（包含展开的子分类） */
    private List<CategoryTypeBean> mCategoryDisplayList = new ArrayList<>();
    /** 原始分类列表（不包含子分类） */
    private List<CategoryTypeBean> mCategoryOriginalList = new ArrayList<>();
    /** 标签列表 */
    private List<LabelBean> mLabelList = new ArrayList<>();
    /** 商品列表 */
    private List<GoodsBean> mGoodsList = new ArrayList<>();
    /** 所有商品（用于搜索和筛选） */
    private List<GoodsBean> mAllGoodsList = new ArrayList<>();

    /** 搜索防抖 */
    private Handler mSearchHandler = new Handler(Looper.getMainLooper());
    private Runnable mSearchRunnable;
    private static final long SEARCH_DELAY = 300;

    /** 排序状态：0-综合降序，1-综合升序，2-价格降序，3-价格升序 */
    private int mSortType = 2;  // 默认价格降序

    /** 来源类型：0-默认（原有流程），1-促销主品，2-促销赠品 */
    private int mSourceType = 0;

    public static void start(Context context) {
        Intent intent = new Intent(context, AddGoodsActivity.class);
        context.startActivity(intent);
    }

    /**
     * 启动选择商品页面（促销活动使用）
     * @param type 1-促销主品，2-促销赠品
     * @param existingGoods 已选商品列表
     */
    public static void start(Context context, int type, List<GoodsBean> existingGoods) {
        Intent intent = new Intent(context, AddGoodsActivity.class);
        intent.putExtra(IntentKey.TYPE, type);
        intent.putExtra(IntentKey.DATA, (java.io.Serializable) existingGoods);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_goods;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSearchEdit = findViewById(R.id.et_search);
        mCategoryRecyclerView = findViewById(R.id.rv_category);
        mLabelRecyclerView = findViewById(R.id.rv_labels);
        mGoodsRecyclerView = findViewById(R.id.rv_goods);
        mRefreshLayout = findViewById(R.id.srl_refresh);
        mEmptyView = findViewById(R.id.empty_view);
        mSortComprehensive = findViewById(R.id.ll_sort_comprehensive);
        mSortPrice = findViewById(R.id.ll_sort_price);
        mComprehensiveUp = findViewById(R.id.iv_comprehensive_up);
        mComprehensiveDown = findViewById(R.id.iv_comprehensive_down);
        mPriceUp = findViewById(R.id.iv_price_up);
        mPriceDown = findViewById(R.id.iv_price_down);
        mOnlyInStockCheckBox = findViewById(R.id.cb_only_in_stock);
        mTotalQuantityView = findViewById(R.id.tv_total_quantity);
        mConfirmButton = findViewById(R.id.btn_confirm);

        // 设置左侧分类RecyclerView
        mCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCategoryAdapter = new CategoryTypeAdapter(this);
        mCategoryAdapter.setOnCategoryClickListener(this);
        mCategoryRecyclerView.setAdapter(mCategoryAdapter);

        // 设置顶部标签RecyclerView（横向）
        LinearLayoutManager labelLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mLabelRecyclerView.setLayoutManager(labelLayoutManager);
        mLabelAdapter = new LabelAdapter(this);
        mLabelAdapter.setOnLabelClickListener(this);
        mLabelRecyclerView.setAdapter(mLabelAdapter);

        // 设置商品RecyclerView
        mGoodsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mGoodsAdapter = new GoodsAdapter(this);
        mGoodsAdapter.setOnQuantityChangeListener(this);
        mGoodsAdapter.setOnGoodsClickListener(this);
        mGoodsRecyclerView.setAdapter(mGoodsAdapter);

        // 设置刷新监听
        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        // 设置点击监听
        setOnClickListener(mSortComprehensive, mSortPrice, mConfirmButton);

        // 设置搜索监听
        setupSearch();

        // 设置复选框监听
        mOnlyInStockCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            filterGoods();
        });
        
        // 默认选中"仅看有货"
        mOnlyInStockCheckBox.setChecked(true);
    }

    @Override
    protected void initData() {
        // 获取来源类型
        mSourceType = getInt(IntentKey.TYPE, 0);

        loadTestCategories();
        loadTestLabels();
        loadTestGoods();
        
        // 如果是促销活动，恢复之前选择的商品数量
        if (mSourceType == 1 || mSourceType == 2) {
            restoreExistingGoods();
        }
        
        // 初始化排序图标
        updateSortIcons();
        
        updateTotalQuantity();
    }

    /**
     * 恢复已选商品的数量
     */
    private void restoreExistingGoods() {
        java.io.Serializable data = getSerializable(IntentKey.DATA);
        if (data instanceof List) {
            List<GoodsBean> existingGoods = (List<GoodsBean>) data;
            
            // 恢复商品数量
            for (GoodsBean existingGoods1 : existingGoods) {
                for (GoodsBean goods : mAllGoodsList) {
                    if (goods.getId().equals(existingGoods1.getId())) {
                        goods.setQuantity(existingGoods1.getQuantity());
                        break;
                    }
                }
            }
            
            mGoodsAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置搜索监听
     */
    private void setupSearch() {
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString().trim();

                if (mSearchRunnable != null) {
                    mSearchHandler.removeCallbacks(mSearchRunnable);
                }

                mSearchRunnable = () -> {
                    if (!TextUtils.isEmpty(keyword)) {
                        // 有输入内容时，重置所有选择状态
                        resetToInitialState();
                        searchGoods(keyword);
                    } else {
                        // 输入为空，恢复显示所有商品
                        filterGoods();
                    }
                };
                mSearchHandler.postDelayed(mSearchRunnable, SEARCH_DELAY);
            }
        });
    }

    /**
     * 重置到初始状态
     */
    private void resetToInitialState() {
        // 1. 重置左侧分类为"全部"
        for (CategoryTypeBean category : mCategoryOriginalList) {
            category.setSelected(false);
            category.setExpanded(false);
        }
        if (!mCategoryOriginalList.isEmpty()) {
            mCategoryOriginalList.get(0).setSelected(true);
        }
        updateCategoryDisplay();

        // 2. 重置顶部标签为"全部"
        for (LabelBean label : mLabelList) {
            label.setSelected(false);
        }
        if (!mLabelList.isEmpty()) {
            mLabelList.get(0).setSelected(true);
        }
        mLabelAdapter.notifyDataSetChanged();

        // 3. 重置排序为价格降序
        mSortType = 2;
        updateSortIcons();

        // 4. 重新勾选"仅看有货"
        mOnlyInStockCheckBox.setChecked(true);
    }

    /**
     * 搜索商品
     */
    private void searchGoods(String keyword) {
        List<GoodsBean> searchResults = new ArrayList<>();
        
        for (GoodsBean goods : mAllGoodsList) {
            if (goods.getName().contains(keyword) || goods.getCode().contains(keyword)) {
                searchResults.add(goods);
            }
        }

        mGoodsList = searchResults;
        mGoodsAdapter.setData(mGoodsList);

        // 显示/隐藏空数据
        if (mGoodsList.isEmpty()) {
            mEmptyView.show();
            mEmptyView.setHint("未找到相关商品");
        } else {
            mEmptyView.hide();
        }
    }

    /**
     * 筛选商品
     */
    private void filterGoods() {
        // 获取选中的分类
        String selectedCategoryId = getSelectedCategoryId();
        // 获取选中的标签
        String selectedLabelId = getSelectedLabelId();
        // 是否仅看有货
        boolean onlyInStock = mOnlyInStockCheckBox.isChecked();

        List<GoodsBean> filteredList = new ArrayList<>();

        for (GoodsBean goods : mAllGoodsList) {
            // 这里可以根据实际业务逻辑筛选
            // 暂时显示所有商品
            if (onlyInStock && !goods.hasStock()) {
                continue;
            }
            filteredList.add(goods);
        }

        // 排序
        sortGoods(filteredList);

        mGoodsList = filteredList;
        mGoodsAdapter.setData(mGoodsList);

        // 显示/隐藏空数据
        if (mGoodsList.isEmpty()) {
            mEmptyView.show();
        } else {
            mEmptyView.hide();
        }
    }

    /**
     * 商品排序
     */
    private void sortGoods(List<GoodsBean> list) {
        // 根据排序类型排序（这里需要实际的排序字段，暂时按价格排序）
        // 实际项目中可能需要添加综合排序字段
    }

    /**
     * 获取选中的分类ID
     */
    private String getSelectedCategoryId() {
        for (CategoryTypeBean category : mCategoryDisplayList) {
            if (category.isSelected()) {
                return category.getId();
            }
        }
        return "all";
    }

    /**
     * 获取选中的标签ID
     */
    private String getSelectedLabelId() {
        for (LabelBean label : mLabelList) {
            if (label.isSelected()) {
                return label.getId();
            }
        }
        return "all";
    }

    /**
     * 更新分类显示列表（展开/收起）
     */
    private void updateCategoryDisplay() {
        mCategoryDisplayList.clear();
        
        for (CategoryTypeBean category : mCategoryOriginalList) {
            mCategoryDisplayList.add(category);
            
            // 如果展开且有子分类，添加子分类
            if (category.isExpanded() && category.isHasChildren()) {
                mCategoryDisplayList.addAll(category.getChildren());
            }
        }
        
        mCategoryAdapter.setData(mCategoryDisplayList);
    }

    // ========== CategoryTypeAdapter 回调 ==========

    @Override
    public void onCategoryClick(int position) {
        CategoryTypeBean clickedCategory = mCategoryDisplayList.get(position);

        // 如果是父分类
        if (!clickedCategory.isChild()) {
            // 取消所有选中状态
            for (CategoryTypeBean category : mCategoryOriginalList) {
                category.setSelected(false);
                // 如果点击的不是当前展开的分类，收起其他分类
                if (!category.getId().equals(clickedCategory.getId())) {
                    category.setExpanded(false);
                }
            }

            // 设置当前分类选中
            clickedCategory.setSelected(true);

            // 如果有子分类，切换展开/收起状态
            if (clickedCategory.isHasChildren()) {
                clickedCategory.setExpanded(!clickedCategory.isExpanded());
            }
        } else {
            // 如果是子分类，选中子分类，取消父分类选中
            for (CategoryTypeBean category : mCategoryOriginalList) {
                category.setSelected(false);
                // 取消子分类的选中状态
                if (category.isHasChildren()) {
                    for (CategoryTypeBean child : category.getChildren()) {
                        child.setSelected(false);
                    }
                }
            }
            clickedCategory.setSelected(true);
        }

        // 更新显示
        updateCategoryDisplay();
        
        // 刷新商品列表
        filterGoods();
    }

    // ========== LabelAdapter 回调 ==========

    @Override
    public void onLabelClick(int position) {
        // 取消所有选中
        for (LabelBean label : mLabelList) {
            label.setSelected(false);
        }
        
        // 选中当前
        mLabelList.get(position).setSelected(true);
        mLabelAdapter.notifyDataSetChanged();
        
        // 刷新商品列表
        filterGoods();
    }

    // ========== GoodsAdapter 回调 ==========

    @Override
    public void onQuantityChanged() {
        updateTotalQuantity();
    }

    @Override
    public void onStockInsufficient(String goodsName) {
        toast(String.format(getString(R.string.stock_insufficient), goodsName));
    }

    @Override
    public void onDeleteGoods(int position) {
        // AddGoodsActivity 不需要删除功能
    }

    @Override
    public void onGoodsClick(int position) {
        // 点击商品，跳转到详情页
        GoodsBean goods = mGoodsAdapter.getItem(position);
        GoodsDetailsActivity.start(this, goods.getId(), goods.getName());
    }

    /**
     * 更新排序图标
     */
    private void updateSortIcons() {
        switch (mSortType) {
            case 0: // 综合降序
                mComprehensiveUp.setImageResource(R.drawable.arrow_shang2);
                mComprehensiveDown.setImageResource(R.drawable.arrow_xia_red);
                // 价格未激活，都是灰色
                mPriceUp.setImageResource(R.drawable.arrow_shang2);
                mPriceDown.setImageResource(R.drawable.arrow_xia2_ic);
                break;
            case 1: // 综合升序
                mComprehensiveUp.setImageResource(R.drawable.arrow_shang_red);
                mComprehensiveDown.setImageResource(R.drawable.arrow_xia2_ic);
                // 价格未激活，都是灰色
                mPriceUp.setImageResource(R.drawable.arrow_shang2);
                mPriceDown.setImageResource(R.drawable.arrow_xia2_ic);
                break;
            case 2: // 价格降序
                // 综合未激活，都是灰色
                mComprehensiveUp.setImageResource(R.drawable.arrow_shang2);
                mComprehensiveDown.setImageResource(R.drawable.arrow_xia2_ic);
                mPriceUp.setImageResource(R.drawable.arrow_shang2);
                mPriceDown.setImageResource(R.drawable.arrow_xia_red);
                break;
            case 3: // 价格升序
                // 综合未激活，都是灰色
                mComprehensiveUp.setImageResource(R.drawable.arrow_shang2);
                mComprehensiveDown.setImageResource(R.drawable.arrow_xia2_ic);
                mPriceUp.setImageResource(R.drawable.arrow_shang_red);
                mPriceDown.setImageResource(R.drawable.arrow_xia2_ic);
                break;
        }
    }

    /**
     * 更新底部总数量
     */
    private void updateTotalQuantity() {
        int total = 0;
        for (GoodsBean goods : mAllGoodsList) {
            total += goods.getQuantity();
        }
        mTotalQuantityView.setText(getString(R.string.quantity_colon) + total);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.ll_sort_comprehensive) {
            // 点击综合排序
            if (mSortType == 0 || mSortType == 1) {
                // 当前是综合排序，切换升序/降序
                mSortType = (mSortType == 0) ? 1 : 0;
            } else {
                // 当前是价格排序，切换到综合降序
                mSortType = 0;
            }
            updateSortIcons();
            filterGoods();
            
        } else if (viewId == R.id.ll_sort_price) {
            // 点击价格排序
            if (mSortType == 2 || mSortType == 3) {
                // 当前是价格排序，切换升序/降序
                mSortType = (mSortType == 2) ? 3 : 2;
            } else {
                // 当前是综合排序，切换到价格降序
                mSortType = 2;
            }
            updateSortIcons();
            filterGoods();
            
        } else if (viewId == R.id.btn_confirm) {
            // 确定按钮
            onConfirm();
        }
    }

    /**
     * 确定按钮点击
     */
    private void onConfirm() {
        // 收集选中的商品
        List<GoodsBean> selectedGoods = new ArrayList<>();
        for (GoodsBean goods : mAllGoodsList) {
            if (goods.getQuantity() > 0) {
                selectedGoods.add(goods);
            }
        }

        if (selectedGoods.isEmpty()) {
            toast("请选择商品");
            return;
        }

        int varietyCount = selectedGoods.size();  // 品种数量
        int totalCount = 0;  // 商品总数
        for (GoodsBean goods : selectedGoods) {
            totalCount += goods.getQuantity();
        }

        if (mSourceType == 1 || mSourceType == 2) {
            // 促销活动流程：跳转到促销主品/赠品页面，传递商品数据
            PromotionProductActivity.start(this, mSourceType, selectedGoods);
        } else {
            // 原有流程：发送事件，结束页面
            EventBusUtil.sendEvent(new EventBean(EventCode.GOODS_SELECTED, selectedGoods));
            toast("已选择" + selectedGoods.size() + "种商品");
            finish();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        // 下拉刷新
        mGoodsAdapter.setPageNumber(1);
        loadTestGoods();
        filterGoods();
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        // 上拉加载更多
        mGoodsAdapter.setPageNumber(mGoodsAdapter.getPageNumber() + 1);
        // TODO: 加载更多数据
        refreshLayout.finishLoadMore();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSearchRunnable != null) {
            mSearchHandler.removeCallbacks(mSearchRunnable);
            mSearchRunnable = null;
        }
    }

    /**
     * 加载测试分类数据
     */
    private void loadTestCategories() {
        mCategoryOriginalList.clear();

        // 全部
        CategoryTypeBean all = new CategoryTypeBean("all", "全部");
        all.setSelected(true);  // 默认选中
        mCategoryOriginalList.add(all);

        // 休闲零食
        mCategoryOriginalList.add(new CategoryTypeBean("snacks", "休闲零食"));

        // 零食礼包
        mCategoryOriginalList.add(new CategoryTypeBean("gift", "零食礼包"));

        // 健康生鲜（有子分类）
        CategoryTypeBean fresh = new CategoryTypeBean("fresh", "健康生鲜");
        fresh.addChild(new CategoryTypeBean("tofu", "豆腐"));
        fresh.addChild(new CategoryTypeBean("dried_tofu", "豆干"));
        fresh.addChild(new CategoryTypeBean("rice_wine", "酒酿"));
        mCategoryOriginalList.add(fresh);

        // 豆腐干
        mCategoryOriginalList.add(new CategoryTypeBean("dried_bean_curd", "豆腐干"));

        // 冰爽一夏（有子分类）
        CategoryTypeBean summer = new CategoryTypeBean("summer", "冰爽一夏");
        summer.addChild(new CategoryTypeBean("snowflake", "雪花"));
        summer.addChild(new CategoryTypeBean("pure_draft", "纯生"));
        summer.addChild(new CategoryTypeBean("dayao", "大窑"));
        mCategoryOriginalList.add(summer);

        // 腐乳系列（有子分类）
        CategoryTypeBean fermented = new CategoryTypeBean("fermented", "腐乳系列");
        fermented.addChild(new CategoryTypeBean("laoganma", "老干妈"));
        fermented.addChild(new CategoryTypeBean("wangzhihe", "王致和"));
        mCategoryOriginalList.add(fermented);

        // 有机系列
        mCategoryOriginalList.add(new CategoryTypeBean("organic", "有机系列"));

        // 健康饮品
        mCategoryOriginalList.add(new CategoryTypeBean("drinks", "健康饮品"));

        // 绿植花卉
        mCategoryOriginalList.add(new CategoryTypeBean("plants", "绿植花卉"));

        updateCategoryDisplay();
    }

    /**
     * 加载测试标签数据
     */
    private void loadTestLabels() {
        mLabelList.clear();
        mLabelList.add(new LabelBean("all", "全部", true));  // 默认选中
        mLabelList.add(new LabelBean("recent", "最近"));
        mLabelList.add(new LabelBean("promotion", "促销"));
        mLabelList.add(new LabelBean("new", "新品"));
        mLabelList.add(new LabelBean("popular", "同行热卖"));
        mLabelAdapter.setData(mLabelList);
    }

    /**
     * 加载测试商品数据
     */
    private void loadTestGoods() {
        mAllGoodsList.clear();
        
        Random random = new Random();
        
        // 商品名称库（用于随机生成，方便测试搜索）
        String[] names = {
            "有机豆腐", "嫩豆腐", "老豆腐", "内酯豆腐", "日本豆腐",
            "五香豆干", "麻辣豆干", "香辣豆干", "原味豆干", "黑豆干",
            "桂花酒酿", "原味酒酿", "红枣酒酿", "糯米酒酿",
            "雪花啤酒", "纯生啤酒", "大窑汽水", "王老吉凉茶",
            "老干妈豆豉", "王致和腐乳", "有机豆浆", "有机豆奶",
            "桂花茶", "菊花茶", "绿茶", "红茶",
            "多肉植物", "绿萝", "发财树", "幸福树"
        };

        // 卖点库
        String[] sellingPoints = {
            "轻食搭档皮薄多汁|健康解馋选择",
            "精选大豆|传统工艺|口感细腻",
            "有机认证|无添加|营养丰富",
            "新鲜直达|品质保证|每日现做",
            "麻辣鲜香|佐餐必备|经典口味"
        };

        // 保质期库
        String[] shelfLifes = {
            "冷藏8天", "冷藏7天", "冷藏10天", "冷藏15天", "常温30天", "常温60天"
        };

        // 单位库
        String[] units = {
            "箱", "包", "盒", "瓶", "袋", "罐"
        };

        // 生成30个测试商品
        for (int i = 0; i < 30; i++) {
            GoodsBean goods = new GoodsBean();
            goods.setId("goods_" + i);
            goods.setName(names[random.nextInt(names.length)]);
            
            // 部分商品有促销标签
            if (random.nextBoolean()) {
                goods.setTag("促销");
            }
            
            goods.setSellingPoint(sellingPoints[random.nextInt(sellingPoints.length)]);
            goods.setStock(random.nextInt(11));  // 0-10 随机库存
            goods.setShelfLife(shelfLifes[random.nextInt(shelfLifes.length)]);
            goods.setCode("1011010" + String.format("%02d", i));
            goods.setPrice("¥" + (10 + random.nextInt(40)) + "." + random.nextInt(10));
            goods.setUnit(units[random.nextInt(units.length)]);  // 随机单位
            
            mAllGoodsList.add(goods);
        }

        filterGoods();
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(EventBean event) {
        if (event.getCode() == EventCode.PROMOTION_GOODS_CHANGED) {
            // 接收促销商品变更事件，关闭页面
            finish();
        }
    }
}

